<template>
  <el-card shadow="never" class="border-0">
    <list-header @create="handleCreate" @refresh="getData" />

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="优惠卷名称" width="350">
        <template #default="{ row, index }">
          <div
            class="border border-dashed py-2 px-4 rounded"
            :class="row.statusText === '领取中' ? 'active' : 'inactive'"
          >
            <h5 class="font-bold text-md">{{ row.name }}</h5>
            <small>{{ row.start_time }} ~ {{ row.end_time }}</small>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="statusText" label="状态" width="380" />
      <el-table-column label="优惠">
        <template #default="{ row, index }">
          {{ row.type === 0 ? '满减' : '折扣' }}
          {{ row.type === 0 ? '￥' + row.value : row.value + '折' }}
        </template>
      </el-table-column>
      <el-table-column prop="total" label="发放数量" />
      <el-table-column prop="used" label="已使用" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            v-if="scope.row.statusText === '未开始'"
            type="primary"
            size="small"
            text
            @click="handleEdit(scope.row)"
          >
            修改
          </el-button>

          <el-popconfirm
            v-if="scope.row.statusText !== '领取中'"
            title="是否删除该优惠卷？ "
            confirmButtonText="删除"
            cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" text> 删除 </el-button>
            </template>
          </el-popconfirm>

          <el-popconfirm
            v-if="scope.row.statusText === '领取中'"
            title="是否要让该优惠卷失效？ "
            confirmButtonText="失效"
            cancelButtonText="取消"
            @confirm="handleStatusChange(0, scope.row)"
          >
            <template #reference>
              <el-button type="danger" size="small"> 失效 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="limit"
        @current-change="getData"
      />
    </div>

    <FormDrawer
      ref="formDrawerRef"
      :title="drawerTitle"
      @submit="handleSumbit"
      @cancel="handleCancel"
    >
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        label-width="100px"
        :inline="false"
      >
        <el-form-item label="优惠卷名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入优惠卷名称"
            style="width: 50%"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">满减</el-radio>
            <el-radio :label="1">折扣</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="面值" prop="value">
          <el-input
            v-model="form.value"
            placeholder="请输入面值"
            style="width: 50%"
          >
            <template #append>
              {{ form.type ? '折扣' : '元' }}
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="发行量" prop="total">
          <el-input-number
            v-model="form.total"
            :min="0"
            :max="10000"
            placeholder="请输入发行量"
          />
        </el-form-item>

        <el-form-item label="最低使用价格" prop="min_price">
          <el-input
            v-model="form.min_price"
            placeholder="请输入最低使用价格"
            type="number"
          />
        </el-form-item>

        <el-form-item label="排序" prop="order">
          <el-input-number
            v-model="form.order"
            :min="0"
            :max="1000"
            placeholder="请输入排序"
          />
        </el-form-item>

        <el-form-item label="活动时间">
          <el-date-picker
            v-model="timerange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :editable="false"
          />
        </el-form-item>

        <el-form-item label="描述" prop="desc">
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>
  import { computed } from 'vue'
  import {
    getCouponListApi,
    createCouponApi,
    updateCouponApi,
    deleteCouponApi,
    updateCouponStatusApi,
  } from '@/api/coupon.js'
  import FormDrawer from '@/components/FormDrawer.vue'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'
  import ListHeader from '@/components/ListHeader.vue'

  function formatStatus(row) {
    let s = '领取中'
    let start_time = new Date(row.start_time).getTime()
    let end_time = new Date(row.end_time).getTime()
    let now = new Date().getTime()

    if (start_time > now) {
      s = '未开始'
    } else if (end_time < now) {
      s = '已结束'
    } else if (row.status === 0) {
      s = '已失效'
    }
    return s
  }

  let { tableData, loading, currentPage, total, limit, getData, handleDelete } =
    useInitTable({
      getlist: getCouponListApi,
      onGetListSuccess: (res) => {
        tableData.value = res.list.map((o) => {
          o.statusText = formatStatus(o)
          return o
        })
        total = res.totalCount
      },
      delete: deleteCouponApi,
      handleStatusChange: updateCouponStatusApi,
    })

  const {
    formRef,
    formDrawerRef,
    form,
    rules,
    drawerTitle,
    editId,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      name: '',
      type: 0,
      value: 0,
      total: 0,
      min_price: 0,
      start_time: null,
      end_time: null,
      order: 50,
      desc: '',
    },
    rules: {
      title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
    },
    getData,
    beforeSumbit: (form) => {
      if (typeof form.start_time !== 'number') {
        form.start_time = new Date(form.start_time).getTime()
      }

      if (typeof form.end_time !== 'number') {
        form.end_time = new Date(form.end_time).getTime()
      }

      return form
    },
    create: createCouponApi,
    update: updateCouponApi,
  })

  // 日期时间
  const timerange = computed({
    get() {
      return form.start_time && form.end_time
        ? [form.start_time, form.end_time]
        : []
    },
    set(val) {
      let start_time = val[0]
      let end_time = val[1]
      form.start_time = start_time
      form.end_time = end_time
    },
  })
</script>

<style scoped>
  .active {
    @apply border-rose-200 bg-rose-50 text-red-400;
  }
  .inactive {
    @apply border-gray-200 bg-gray-50 text-gray-400;
  }
</style>
